package com.xianzhi.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by foreknow on 2021/1/29.
 * 文件操作的工具类
 */
public class FileUtil {
    /**
     * 将MultipartFile保存到指定的路径下
     * @param file
     * @param savePath
     * @return
     * @throws IOException
     */
    public static String save(MultipartFile file,String savePath) throws IOException {
        if (file!=null && file.getSize()>0){
            File fileFolder = new File(savePath);
            if (!fileFolder.exists()){
                fileFolder.mkdirs();
            }
            File saveFile = getFile(savePath,file.getOriginalFilename());
            file.transferTo(saveFile);
            return saveFile.getName();
        }
        return null;
    }



    /**
     * 删除服务器上的文件
     * @param filePath
     * @return boolean   true删除成功   false表示删除失败
     */
    public static boolean delete(String filePath){
        File file = new File(filePath);
        if (file.isFile()){
            file.delete();
            return true;
        }
        return false;
    }

    /**
     * 获取文件的
     * @param savePath
     * @param originalFilename
     * @return
     */
    private static File getFile(String savePath, String originalFilename) {
        String fileName = System.currentTimeMillis()+"_"+originalFilename;
        File file = new File(savePath+fileName);
        if (file.exists()){
            return getFile(savePath,originalFilename);
        }
        return file;
    }
}
